<?php


namespace app\admin\controller;
use com\Encryption;
use app\common\model\Admins;
use app\common\model\AuthGroup;
use app\common\model\AuthGroupAccess;
use app\common\model\AuthRule;

use think\facade\Config;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;

class Admin extends Base
{


    public function index(){
        $pid = Request::param('pid'); //类别pid
        $where = Request::param('where', []);
        $where = array_filter($where);
        $keyword = Request::param('keyword');

        $list = Db::name('admins')
            ->alias('a')
            ->leftJoin('auth_group_access ac', 'a.admin_id = ac.uid')
            ->leftJoin('auth_group ag', 'ac.group_id = ag.id')
            ->field('a.*, ac.group_id, ag.title')
            ->where($where)
            ->where(function ($query) use ($keyword) {
                if (!empty($keyword)) {
                    $query->whereLike('username|title', "%$keyword%");
                }
            })
            ->paginate(10, false, ['query' => request()->param()]);


        $page = $list->render();
        $view = [
            'keyword' => $keyword,
            'page' => $page,
            'list' => $list,
            'pid' => $pid,
        ];
        View::assign($view);
        return View::fetch();
    }
    public function add(){
        if (Request::isPost()){
            $data = Request::post();
            $passwordinfo = Request::param('password','','get_password');
            $data['password'] =  $passwordinfo['password'];
            $data['encrypt'] = $passwordinfo['encrypt'];
            $data['logintime'] = time();
            $data['loginip']   = Request::ip();
            $result = Admins::create($data);
            if ($result) {
                AuthGroupAccess::create([
                    'uid'      =>  $result->id,
                    'group_id' =>  $data['group_id'],
                ]);
                $this->success('管理员添加成功', url('admin/index'));
            } else {
                $this->error('管理员添加失败');
            }
        }else{
            $auth_group = AuthGroup::where('status','=',1)->select();
            $view = [
                'authGroup' => $auth_group,
                'info'      => null,
                'type'=>'添加管理员',
            ];
        }
        View::assign($view);
        return View::fetch();
    }

    // 管理员修改
    public function edit(){
        if (Request::isPost()){
            $data = Request::post();
            $password = $data['password'];
            $map[] = ['admin_id','<>',$data['admin_id']];
            $where['admin_id'] = $data['admin_id'];

            $group_id = $data['group_id'];
            unset($data['group_id']);

            if ($password) {
                $data['password'] = Request::param('password','','get_password');
            }else{
                unset($data['password']);
            }

            Admins::update($data, $where);
            AuthGroupAccess::update([
                'group_id' =>  $group_id
            ], ['uid'=>$data['admin_id']]);
            $this->success('管理员修改成功!', 'index');
        }else{
            $auth_group = AuthGroup::select();
            $admin_id = Request::param('admin_id');
            $admin = Db::name('admins')->find($admin_id);
            $admin['group_id'] = AuthGroupAccess::where('uid', $admin['admin_id'])
                ->value('group_id');
            $view = [
                'info'      => $admin,
                'authGroup' => $auth_group,
                'type'=>'添加管理员',
            ];
        }
        View::assign($view);
        return View::fetch();
    }

    public function del(){
        $admin_id = Request::param('admin_id');
        $adminimages = Db::name('admins')->field('image')->find($admin_id);
        $oldadminImg=ROOT_PATH.$adminimages['image'];
        if(file_exists($oldadminImg)){
            @unlink($oldadminImg);
        }
        if (Db::name('admins')->delete($admin_id)){
            Db::name('auth_group_access')->where('uid',$admin_id)->delete();
            return success('删除用户成功！','index');
        }else{
            return error('删除用户失败！');
        }
    }

    public function pildel(){
        $id = Request::param('id');
        $ids = explode(',',$id);
        foreach($ids as $k=>$v){
            $adminimag = Db::name('admins')->field('image')->find($v);
            $oldadminsImg=ROOT_PATH.$adminimag['image'];
            if(file_exists($oldadminsImg)){
                @unlink($oldadminsImg);
            }
            Db::name('auth_group_access')->where('uid',$v)->delete();
            $res = Db::name('admins')->delete($v);
        }
        if ($res){
            return success('批量删除用户成功！','index');
        }else{
            return error('删除用户失败！');
        }
    }

    public function ajaxUsername ()
    {
        $key = Request::param('name');
        $value = Request::param('param');
        $admin_id = input('admin_id', 0, 'intval');
        $res = Admin::ajaxUsernamexx($value, $admin_id);
        if ($res) {
            $data = array(
                'status' => 'n',
                'info' => '管理员用户名已经重复，请一个试试'
            );
        } else {
            $data = array(
                'status' => 'y',
                'info' => '验证通过'
            );
        }
        return json($data);
    }

    /**
     * ajax验证用户名
     */
    public function ajaxUsernamexx($username,$admin_id = 0){
        if(empty($username)){
            return 1;
        }
        //组装where条件
        $where = array();
        $where[] = array('username','=',$username);
        if($admin_id > 0){
            $where[] =  array('admin_id','<>',$admin_id);
        }
        return Db::name('admins')->where($where)->find();
    }




}